package com.spring.shiro.service;

import com.spring.shiro.entity.Dept;
import com.spring.shiro.mapper.DeptMapper;
import com.spring.shiro.utils.Tree;
import com.spring.shiro.utils.TreeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DeptService {

    @Autowired
    private DeptMapper deptMapper;

    public Tree<Dept> getDeptTree() {

        List<Tree<Dept>> trees = new ArrayList<>();
        Example example = new Example(Dept.class);
        example.setOrderByClause("dept_id");

        List<Dept> depts = deptMapper.selectByExample(example);

        for (Dept dept : depts) {
            Tree<Dept> tree = new Tree<>();
            tree.setId(dept.getDeptId().toString());
            tree.setParentId(dept.getParentId().toString());
            tree.setText(dept.getDeptName());
            trees.add(tree);
        }

        return TreeUtils.build(trees);
    }

    public Dept findById(Long deptId) {
        return this.deptMapper.selectByPrimaryKey(deptId);
    }

    public List<Dept> findAllDepts(Dept dept) {
        try {
            Example example = new Example(Dept.class);
            if (StringUtils.isNotBlank(dept.getDeptName())) {
                example.createCriteria().andCondition("dept_name=", dept.getDeptName());
            }
            example.setOrderByClause("dept_id");
            return this.deptMapper.selectByExample(example);
        } catch (Exception e) {
            log.error("获取部门列表失败", e);
            return new ArrayList<>();
        }
    }

    @Transactional
    public void addDept(Dept dept) {
        Long parentId = dept.getParentId();
        if (parentId == null)
            dept.setParentId(0L);
        dept.setCreateTime(new Date());
        this.deptMapper.insert(dept);
    }

    @Transactional
    public void deleteDepts(String deptIds) {
        List<String> list = Arrays.asList(deptIds.split(","));
        Example example = new Example(Dept.class);
        example.createCriteria().andIn("deptId", list);
        this.deptMapper.deleteByExample(example);

        this.deptMapper.changeToTop(list);
    }

    @Transactional
    public void updateDept(Dept dept) {
        this.deptMapper.updateByPrimaryKeySelective(dept);
    }

}
